package com.winit.openapi.apiadapter.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.outbound.OutboundOrderService;
import com.winit.oms.spi.outbound.command.order.OutboundOrderCommand;
import com.winit.oms.spi.outbound.vo.OutboundOrderVo;
import com.winit.openapi.apiadapter.controller.builder.OrderAdapteBuilder;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 查询出库单详细信息接口适配
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2017年2月7日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
public class QueryOutboundOrderDetailAdapteController extends AbstractAdapteController {

    @Resource
    private OutboundOrderService outboundOrderService;

    @Resource
    private OrderAdapteBuilder   orderAdapteBuilder;

    /**
     * 出库单详情查询
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryOutboundOrder")
    public String queryOutboundOrderDetail(@ModelAttribute RequestMsg requestMsg,
                                           @ModelAttribute ResponseMsg responseMsg) {

        return doAdapte(requestMsg, responseMsg);
    }

    /**
     * 查询出库单详情接口校验 1、 不传出库单号，也不传开始和结束时间，系统报错
     * 2、不传出库单号，传开始和结束，可以查旧系统列表，但时间区间不能超过3个月，否则报错 3、 传新系统单号，查新系统订单详情
     * 4、传旧系统单号，查旧系统详情
     * 
     * @param json
     * @throws ParseException
     */
    @Override
    protected void validateInputJson(RequestMsg requestMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        if (null == json) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        String orderNo = json.getString("outboundOrderNum");
        String startDate = json.getString("startDate");
        String endDate = json.getString("endDate");
        // 单号和时间均不传，直接报错返回
        if (StringUtils.isBlank(orderNo) && StringUtils.isBlank(startDate) && StringUtils.isBlank(endDate)) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "outboundOrderNum and startDate and endDate");
        }
        if (orderNo != null && orderNo.isEmpty()) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "outboundOrderNum");
        }

        ValidateUtil.validMaxLength(json, "outboundOrderNum", 64);
        ValidateUtil.validByRegex(json, "shareOrderType", "[0123]", false);

        if (json.containsKey("startDate") && json.containsKey("endDate")) {
            ValidateUtil.validDateString(json, "startDate", "yyyy-MM-dd");
            ValidateUtil.validDateString(json, "endDate", "yyyy-MM-dd");
            ValidateUtil.validDateBefore(json, "startDate", "endDate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();

            try {
                c1.setTime(sdf.parse(json.getString("startDate")));
                c2.setTime(sdf.parse(json.getString("endDate")));
            } catch (ParseException e) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "startDate or endDate");
            }
            int month = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12
                        + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH));
            if (3 <= month) {
                throw new ApiException(ErrorCode.QUERY_TIME_TOO_LONG_ERROR);
            }
        } else if (json.containsKey("startDate") || json.containsKey("endDate")) {

            throw new ApiException(ErrorCode.FIELD_NOT_NULL, json.containsKey("startDate") ? "endDate" : "startDate");
        }

        if (json.containsKey("pageSize")) {
            ValidateUtil.validInteger(json, "pageSize", true);
            ValidateUtil.validNumberBiggerThanZero(json, "pageSize");
        }
        if (json.containsKey("pageNum")) {
            ValidateUtil.validInteger(json, "pageNum", true);
            ValidateUtil.validNumberBiggerThanZero(json, "pageNum");
        }

    }

    @Override
    protected boolean checkCustomerTansferConfig(RequestMsg requestMsg, ResponseMsg responseMsg) {
//        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
//
//        if (json.containsKey("outboundOrderNum")) {
//            String orderNo = json.getString("outboundOrderNum");
//            if (orderNo.startsWith("WO")) {
//                return true;
//            }
//        }

        return true;

    }

    @Override
    protected void doAdapteInOpenAPI(RequestMsg requestMsg, ResponseMsg responseMsg) {

        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        String orderNo = json.getString("outboundOrderNum");

        OutboundOrderCommand command = new OutboundOrderCommand();
        OutboundOrderVo vo = new OutboundOrderVo();
        vo.setOrderNo(orderNo);
        command.setOrder(vo);
        command.setCtx(CommandContext.getContext());

        OutboundOrderVo outboundOrderVo = outboundOrderService.queryOrderByOrderNo(command);
        if (null == outboundOrderVo) {
            throw new ApiException(ErrorCode.ORDER_NO_NOT_EXSIT, orderNo);
        }

        JSONObject resultJson = orderAdapteBuilder.buildPagePara(requestMsg, responseMsg);
        responseMsg.setData(resultJson);
        List<Map<String, Object>> result = orderAdapteBuilder.buildOrderDetailResult(outboundOrderVo);
        if (null != result) {
            resultJson.put("list", result);
            resultJson.put("total", result.size());
        }

    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.setTime(sdf.parse("2017-02-01"));
        c2.setTime(sdf.parse("2017-05-01"));

        int month = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12
                    + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH));
        System.err.println(month);
    }
}
